import 'package:dio/dio.dart';
import '../utils/config.dart';

class HttpRequest {
  static final BaseOptions baseOptions = BaseOptions(
      baseUrl: HttpConfig.baseUrl, connectTimeout: HttpConfig.timeout);
  static final Dio dio = Dio(baseOptions);

  static Future<T> request<T>(String url,
      {String method = 'get',
      Map<String, dynamic> params,
      Interceptor interceptor}) async {
    //1.创建单独配置
    final options = Options(method: method);

    //全局拦截器
    //创建默认的全局拦截器
    Interceptor inter = InterceptorsWrapper(onRequest: (options) {
      // print('interceptor request:$options');
      return options;
    }, onResponse: (response) {
      // print('interceptor response:$response');
      return response;
    }, onError: (err) {
      print('interceptor err$err');
      return err;
    });
    List<Interceptor> inters = [inter];
    if (interceptor != null) {
      inters.add(interceptor);
    }
    dio.interceptors.addAll(inters);

    //2.发送网络请求
    try {
      Response response =
          await dio.request(url, queryParameters: params, options: options);
      return response.data;
    } on DioError catch (e) {
      return Future.error(e);
    }
  }
}
